package com.mt.filter;

import cn.hutool.core.util.StrUtil;
import com.mt.constants.Result;
import com.mt.enums.AclType;
import com.mt.enums.Status;
import com.mt.exception.GlobalException;
import com.mt.feign.UserApiProvider;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Wang
 * @Description 登录token验证过滤
 * @date 2020/11/9-15:46
 */
@Slf4j
@Component
public class preLoginFilter extends ZuulFilter {
    @Resource
    UserApiProvider userApiProvider;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        log.info("进入网关拦截器");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //区分get / post请求
        String type = request.getMethod();
        String url = request.getRequestURI();

        String code = request.getParameter("code") ==
                null ? "" : request.getParameter("code");
        AclType.getAclType(type);
        String token = request.getHeader("x-token");
        String substring = url.substring(url.lastIndexOf("/") + 1);
        if ("login".equals(substring) || "register".equals(substring)) {
            return null;
        }
        if (StrUtil.isBlank(token)) {
            log.info("用户未登录,转发");
        } else {
            String authId = null;
            Result<String> auth =
                    userApiProvider.AuthUser(token, type, url, code);
            if ( Status.SUCCESS.getCode().equals(auth.getCode() )){
                authId =  auth.getData();
            }
            if (authId == null) {
                throw new GlobalException(Status.AUTH_ERROR);
            } else {
                //验证token完毕后,添加id参数
                Map<String, List<String>> requestQueryParams =
                        ctx.getRequestQueryParams();
                if (requestQueryParams == null) {
                    requestQueryParams = new HashMap<>();
                }
                ArrayList<String> paramsList = new ArrayList<>();
                //这里传参数id的值
                paramsList.add(authId);
                requestQueryParams.put("userId", paramsList);
                ctx.setRequestQueryParams(requestQueryParams);
            }
        }
        return null;
    }
}
